<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\model;

use \think\Model;
use app\admin\model\Goods as G;
class Theme extends Model
{
    public function attachment()
    {
        //关联附件表
        return $this->belongsTo('Attachment','thumb');
    }
    public function attachment1()
    {
        //关联附件表
        return $this->belongsTo('Attachment','thumb1');
    }

    public function getThemeSortGoods($theme,$field='g.goods_id',$where='')
    {
        //初始化模型
        $model = new G();
        //关联城市和是基本搜索条件
        $model = $model->where([
            'g.goods_status'=>1,
            'g.show'=>1
        ])->where($where)->alias('g')
            ->join('city c','c.id=g.city_id','left')
            ->field($field);
        //验证是否存在tag_id并检索
        if(isset($theme['tag_id']) && !empty($theme['tag_id'])){
            $tag = explode(",",$theme['tag_id']);
            //过滤已启用的tag_id
            $tagList = db("tag")->field("tag_id")->where(['tag_id'=>['in',$tag],'tag_status'=>1])->select();
            $tag = array_column($tagList,"tag_id");
            if(!empty($tag)){
                $model->where(function ($query) use ($tag){
                    foreach ($tag as $value){
                        $query->whereOr('find_in_set('.$value.',tag_id)');
                    }
                });
            }
        }
        //验证是否需要排序
        if(isset($theme['sort']) && !empty($theme['sort'])){
            //用于排序
            $whereid = array_reverse(explode(',',$theme['sort']));
            $whereid = implode(",",$whereid);
            $exp =new \think\db\Expression("field(g.goods_id,".$whereid.") desc,g.goods_id desc");
            $model->order($exp);
        }else{
            $model->order("g.goods_id desc");

        }

        return $model;
    }

}
